var toPage;
$(function () {
    getEnterpriseList();
    formValidation();
    $('#validationCustom4').hide();
});

function getEnterpriseList(_pageIndex) {
    $('#addInfoModal').modal('hide');
    showLoading(LOADING);
    let searchValue = $('#searchValue').val();
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    $('#enterpriseList tbody').empty();
    getJson("/sys/org/list", {
        searchValue: searchValue,
        type: '0',
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (data) {
        let payload = data['payload'];
        $("#page").paging({
            pageNo: pageIndex,
            totalPage: payload['pages'],
            totalSize: payload['total'],
            callback: function (num) {
                getEnterpriseList(num);
            }
        });
        let order = 1 + 10 * (pageIndex - 1);
        for (let item of payload['data']) {
            item['order'] = order++;
        }
        buildTable($('#enterpriseList'), title, label, payload['data'], function (td, label, item) {
            switch (label) {
                case 'position':
                    let position = item['province'] + item['city'] + (isNull(item['county']) ? '' : item['county']) + item['address'].split(item['city']).join('').split(item['county']).join('').split(item['province']).join('');
                    $(td).text(position);
                    break;
                case 'logo':
                    $(td).empty();
                    if (!isNull(item['logo'])) {
                        let logo = createElement('img', td);
                        $(logo).addClass('img-preview');
                        $(logo).attr('src', fileUrl + concatMinImgUrl(item['logo']));
                        $(logo).attr('data-origin', fileUrl + item['logo']);
                    }
                    break;
                case 'photo':
                    $(td).empty();
                    if (!isNull(item['photo'])) {
                        let photo = createElement('img', td);
                        $(photo).addClass('img-preview');
                        $(photo).attr('src', fileUrl + concatMinImgUrl(item['photo']));
                        $(photo).attr('data-origin', fileUrl + item['photo']);
                    }
                    break;
                case 'opera':
                    if (enterpriseInfoOpera) {
                        let edit = createElement('a', td);
                        $(edit).addClass('font-p24');
                        $(edit).attr('href', '##');
                        $(edit).click(function () {
                            editInfo(item['id']);
                        });
                        let del = createElement('a', td);
                        $(del).addClass('font-p24').addClass('delete-option-btn').addClass('ml-2');
                        $(del).attr('href', '##');
                        $(del).click(function () {
                            deleteInfo(item['id']);
                        });
                        let editIcon = createElement('i', edit);
                        $(editIcon).addClass('iconfont').addClass('icon-bianji-');
                        let delIcon = createElement('i', del);
                        $(delIcon).addClass('iconfont').addClass('icon-shanchuicon');
                    }
                    break;
            }
        });
        hideLoading();
    })
}

$("#page").paging({
    pageNo: 1,
    totalPage: 1,
    totalSize: 1,
    callback: function (num) {
    }
});

$('#addInfoModal').on('hidden.bs.modal', function () {
    let form = $("#addInfoForm");
    form.data('bootstrapValidator').destroy();
    // $('#addInfoForm').data('bootstrapValidator', null);
    formValidation();
    form[0].reset();//清空表单
    resetForm(form);
});

function formValidation() {
    $('#addInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',
            validating: 'fa fa-sync-alt'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 50,
                    }
                }
            },
            province: {
                validators: {
                    callback: {
                        message: '请选择省份',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#validationCustom02'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, city: {
                validators: {
                    callback: {
                        message: '请选择市',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#validationCustom03'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, address: {
                validators: {
                    notEmpty: {
                        message: '请输入详细地址'
                    },
                }
            },
            contact: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 50
                    },
                    regexp: {
                        regexp: /^[\u4E00-\u9FA5a-zA-Z_\-\s]+$/,
                        message: '联系人只能由汉字、字母、横线和下划线组成'
                    },
                }
            },
            phone: {
                validators: {
                    notEmpty: {},
                    regexp: {
                        // regexp: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
                        regexp: /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/,
                        message: '请输入正确的手机号'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        showLoading("正在提交中");
        //防止表单提交
        e.preventDefault();
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        jQuery.support.cors = true;
        var bv = $form.data('bootstrapValidator');
        var formdata = new FormData($("#addInfoForm")[0]);
        compressPicture($('#add_file_hide').prop('files')[0], 100, 100, 0.75, function (logo) {
            if (!isNull(logo)) {
                formdata.append("minLogo", logo);
            }
            compressPicture($('#add_file_hide2').prop('files')[0], 100, 100, 0.75, function (photo) {
                if (!isNull(photo)) {
                    formdata.append("minPhoto", photo);
                }
                ////使用Ajax提交表单数据
                $.ajax({
                    url: host + "/sys/org/save",
                    type: 'POST',
                    data: formdata,
                    contentType: false,
                    processData: false,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('token', sessionStorage.getItem("token"));
                    },
                    success: function (data) {
                        hideLoading();
                        if (data.code == 200) {
                            myAlert("提示", "保存成功", function () {
                                getEnterpriseList(toPage);
                                return;
                            })
                        }
                        myAlert("提示", data.message)
                    },
                    error: function (data) {
                        hideLoading();
                        myAlert("提示", "保存失败")
                    }
                });
            });
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

$('#validationCustom03').change(function () {
    getCounty(getSelectValue($('#validationCustom02')), getSelectValue($('#validationCustom03')), $('#validationCustom4'));
})

/*添加*/
function addInfo() {
    $('#id-id').val('');
    $('#validationCustom04').empty();
    getProvince($('#validationCustom02'));
    $('#validationCustom02').find('option').each(function () {
        $(this).removeAttr('selected');
    });
    buildSelect($('#validationCustom03'));
    buildSelect($('#validationCustom4'));
    $('#addInfoForm')[0].reset();//清空表单
    $('#img_load_area').attr('src', '../customize/images/icon/image-upload.png')
    $('#img_load_area2').attr('src', '../customize/images/icon/image-upload.png')
    $('#modal_title').text('添加企业');
    $('#addInfoModal').modal();
}

function getCityL(val, e) {
    getCity(val, e);
    $('#validationCustom4').hide();
    createElementNoData("option", $('#validationCustom4'), "请选择", null);
    $('#validationCustom08').attr("style", "");
    $('#validationCustom09').attr("style", "");
}

/*修改信息*/
function editInfo(e) {
    getJson("/enterprise/getInfoById",{"id": e}, 'GET',function (result) {
        $('#modal_title').text('修改企业信息');
        $('#type-id').val(1);
        $('#id-id').val(e);
        $('#validationCustom01').val(result.name);
        getProvince($('#validationCustom02'), result['province'], $('#validationCustom03'), result['city'], $('#validationCustom4'), result['county']);
        $('#validationCustom04').text(result.address);
        if (isNull(result.logo)) {
            $('#img_load_area').attr("src", '../customize/images/icon/image-upload.png');
        } else {
            $('#img_load_area').attr("src", fileUrl + result.logo);
        }
        if (isNull(result.photo)) {
            $('#img_load_area2').attr("src", '../customize/images/icon/image-upload.png');
        } else {
            $('#img_load_area2').attr("src", fileUrl + result.photo);
        }
        $('#validationCustom06').val(result.contact);
        $('#validationCustom07').val(result.phone);
        $('#validationCustom05').val(result.position);
        $('#validationCustom08').val(result.culture);
        $('#validationCustom09').val(result.introduction);
        $('#addInfoModal').modal();
    });

}

/*删除信息*/
function deleteInfo(e) {
    myConfirm("提示", "您是否要删除此企业信息", function (res) {
        if (res) {
            getJson("/enterprise/deleteInfoById",{"id": e},'GET',function (result) {
                if (result.code == 200) {
                    myAlert("提示", "删除成功", function () {
                        getEnterpriseList(toPage);
                    })
                } else {
                    myAlert("提示", result.message);
                }
            })
        }
    })
}

$('#add_file_hide').change(function (e) {
    if (this.files[0].size / 1024 / 1024 > 10) {
        myAlert("提示", "选择的图片不能超过10M");
        return;
    }
    var _URL = window.URL || window.webkitURL;
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            $('#img_load_area').attr('src', this.src);
        };
        img.src = _URL.createObjectURL(file);
    }
});

$('#add_file_hide2').change(function (e) {
    if (this.files[0].size / 1024 / 1024 > 10) {
        myAlert("提示", "选择的图片不能超过10M");
        return;
    }
    var _URL = window.URL || window.webkitURL;
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            $('#img_load_area2').attr('src', this.src);
        };
        img.src = _URL.createObjectURL(file);
    }
});
